package com.flower.subject.infra.config;

import com.flower.subject.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;


/**
 * @author lavender
 * @version 1.0
 * @date 2024-07-27 21:18
 * 填充公共字段信息的拦截器
 */
@Component
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})

})
public class MybatisInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        log.info("拦截器：{}",mappedStatement.getId());
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if(parameter == null){
            return invocation.proceed();
        }
        // 获取当前登录用户的id
        String loginId = LoginUtil.getLoginId();
        if(StringUtils.isBlank(loginId)){
            return invocation.proceed();
        }
        if(SqlCommandType.INSERT == sqlCommandType || sqlCommandType.UPDATE == sqlCommandType){
            replaceEntityProperty(parameter,loginId,sqlCommandType);
        }


        return invocation.proceed();
    }

    private void replaceEntityProperty(Object parameter, String loginId, SqlCommandType sqlCommandType) {
       if(parameter instanceof Map){
           replaceMap((Map) parameter,loginId,sqlCommandType);
       }else {
           replace(parameter,loginId,sqlCommandType);
       }

    }

    private void replaceMap(Map parameter, String loginId, SqlCommandType sqlCommandType) {
        Collection values = parameter.values();
        for (Object value : values) {
            replace(value,loginId,sqlCommandType);
        }
    }

    private void replace(Object parameter, String loginId, SqlCommandType sqlCommandType) {
        if(SqlCommandType.INSERT == sqlCommandType){
            dealInsert(parameter,loginId);
        }else {
            dealUpdate(parameter,loginId);
        }
    }

    // 插入时候填充属性
    private void dealInsert(Object parameter, String loginId) {
        Field[] allFields = getAllFields(parameter);
        for (Field field : allFields) {

            try {
                // 设置成可访问的
                field.setAccessible(true);
                Object o = field.get(parameter);
                if(Objects.nonNull(o)){
                    field.setAccessible(false);
                    continue;
                }
                if("isDeleted".equals(field.getName())){
                    field.set(parameter,0);
                    field.setAccessible(false);
                }else if("createdBy".equals(field.getName())){
                    field.set(parameter,loginId);
                    field.setAccessible(false);
                }else if ("createdTime".equals(field.getName())){
                    field.set(parameter,new Date());
                    field.setAccessible(false);
                }else {
                    field.setAccessible(false);
                }
            } catch (IllegalAccessException e) {
               log.error("反射获取属性失败",e);
            }
        }
    }


    private void dealUpdate(Object parameter, String loginId) {
        Field[] allFields = getAllFields(parameter);
        for (Field field : allFields) {

            try {
                // 设置成可访问的
                field.setAccessible(true);
                Object o = field.get(parameter);
                if(Objects.nonNull(o)){
                    field.setAccessible(false);
                    continue;
                }
                if("updateBy".equals(field.getName())){
                    field.set(parameter,loginId);
                    field.setAccessible(false);
                }else if ("updateTime".equals(field.getName())){
                    field.set(parameter,new Date());
                    field.setAccessible(false);
                }else {
                    field.setAccessible(false);
                }
            } catch (IllegalAccessException e) {
                log.error("反射获取属性失败",e);
            }
        }
    }

    /**
     * 通过反射获取类的所有属性字段
     * @param object
     * @return
     */
    private Field[] getAllFields(Object object){
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null){
            Field[] fields = clazz.getDeclaredFields();
            fieldList.addAll(new ArrayList<>(Arrays.asList(fields)));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }





}
